//TODO
import webviews from '../webviews.js';
import React, { Component } from 'react';
import classNames from 'classnames';
function OneButton(props) {
  const [state, setState] = React.useState({ active: props.request.granted });
  const getIcons = (request) => {
    if (request.permission === 'notifications') {
      return ['carbon:chat'];
    } else if (request.permission === 'media') {
      var mediaIcons = {
        video: 'carbon:video',
        audio: 'carbon:microphone',
      };
      return request.details.mediaTypes.map((t) => mediaIcons[t]);
    }
  };
  const grantPermission = (permissionId) => {
    this.requests.forEach((request) => {
      if (request.permissionId && request.permissionId === permissionId) {
        ipc.send('permissionGranted', permissionId);
      }
    });
  };
  let cn = classNames({
    'tab-icon': true,
    'permission-request-icon': true,
    active: state.active,
  });
  let icons = getIcons(props.request).forEach((icon) => {
    icons.push(<i className={'i ' + icon} />);
  });
  var button = (
    <button
      onClick={(e) => {
        e.stopPropagation();
        if (props.request.granted) {
          webviews.callAsync(props.tab.id, 'reload');
        } else {
          grantPermission(request.permissionId);
          // button.classList.add('active')
          setState({ active: true });
        }
      }}
      className={cn}
    >
      {icons}
    </button>
  );
  return button;
}
export default class PermissionRequests extends React.Component {
  constructor(props) {
    super();
    this.listeners = [];
    this.state = { requests: [] };
    // PermissionRequests.current = this;
  }
  render() {
    // getButtons: function (tabid) {
    var buttons = [];
    this.requests.forEach(function (request) {
      if (request.tabid === props.tab.id) {
        buttons.push(<OneButton request={request} tab={props.tab} />);
      }
    });
    return buttons;
  }
  // static onChange = (listener) => {
  //   PermissionRequests.current.onChange(listener);
  // };
  onChange = (listener) => {
    this.listeners.push(listener);
  };
  static initialize = () => {
    ipc.on('updatePermissions', (e, data) => {
      var oldData = this.state.requests;
      // this.requests = data
      this.setState({ requests: data });
      oldData.forEach((req) => {
        this.listeners.forEach((listener) => listener(req.tabid));
      });
      this.state.requests.forEach((req) => {
        this.listeners.forEach((listener) => listener(req.tabid));
      });
    });
  };
}
// PermissionRequests.initialize()
